/**
 * File: MaqReadProcessor.java
 * Created by: mhaimel
 * Created on: 7 Jul 2009
 * CVS:  $Id: MaqReadController.java,v 1.2 2009/12/07 09:44:25 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.maq.impl;

import java.util.List;
import java.util.concurrent.Future;

import uk.ac.ebi.curtain.controller.ParallelController;
import uk.ac.ebi.curtain.controller.SimpleReport;
import uk.ac.ebi.curtain.controller.maq.MaqBean;
import uk.ac.ebi.curtain.management.IControllerReport;
import uk.ac.ebi.curtain.management.InterceptorInfo;
import uk.ac.ebi.curtain.processor.maq.impl.MaqReadProcessor;
import uk.ac.ebi.curtain.utils.file.FileInfo;

/**
 * @author mhaimel
 *
 */
public class MaqReadController extends ParallelController<MaqBean, MaqBean, MaqReadProcessor> {
	private int iCnt = 0;

//	@Override
//	public synchronized void handle(MaqBean input, InterceptorInfo info) {
//		for(FileInfo fi : input.getReadFiles()){
//			++iCnt;
//			MaqBean bean = new MaqBean(input);
//			bean.getReadFiles().clear();
//			bean.getReadFiles().add(fi);
//			MaqReadProcessor processor = getContext().getInjector().getInstance(MaqReadProcessor.class);
//			processor.setInput(bean);
//			submit(processor);
//		}
//	}
	
	
	@Override
	protected MaqReadProcessor buildJob(MaqBean input, InterceptorInfo info) {
		++iCnt;
		return getContext().getInjector().getInstance(MaqReadProcessor.class);
//		throw new NotImplementedException("Should not be called - handle overwritten!!!");
	}

	@Override
	protected void processResult(Future<MaqBean> res, MaqReadProcessor job) {
		MaqBean result = extractResult(res, job);
		if(null != result){
			List<FileInfo> bfqList = result.getReadBfqList();
			if(!bfqList.isEmpty()){
				FileInfo sample = bfqList.get(0); // one sample to get filetype
				
				if(sample.getReadType().isPaired()){
					// paired
					if(bfqList.size() > 2){
						// paired, but split
						for(int i = 0; i+1 < bfqList.size(); i += 2 ){
							MaqBean bean = new MaqBean(result);
							bean.getReadBfqList().clear();
							bean.getReadBfqList().add(result.getReadBfqList().get(i));
							bean.getReadBfqList().add(result.getReadBfqList().get(i+1));
							interceptorHandle(bean);
						}
					} else {
						// paired - ready to submit
						interceptorHandle(result);
					}
				} else {
					// unpaired
					if(bfqList.size() > 1){
						// split values -> separate files
						for(FileInfo fi : bfqList){
							MaqBean bean = new MaqBean(result);
							bean.getReadBfqList().clear();
							bean.getReadBfqList().add(fi);
							interceptorHandle(bean);
						}
					} else{
						// unpaired - ready to submit
						interceptorHandle(result);						
					}
				}
			}
		}
	}	

	@Override
	protected IControllerReport getReturnCall() {
		return new SimpleReport("Finished with submitting: " + iCnt);
	}

}
